<template>
	<div>
		<div class="topTitle">视频广告管理</div>
		<el-form inline :model="query" label-width="80px">
			<el-form-item label="广告名称">
				<el-input placeholder="请输入关键字" v-model="query.name" class="width260 margin-right10"></el-input>
			</el-form-item>
			<el-form-item label="广告分类">
				<el-select v-model="query.typeId" placeholder="请选择广告分类" class="width260 margin-right20">
					<el-option v-for="(item,index) in adverTypeData" :key="index" :label="item.name" :value="item.id"></el-option>
				</el-select>
			</el-form-item>
			<el-button type="primary" icon="el-icon-search" class="margin-left10" @click="handleSearch">搜索</el-button>
			<el-button type="default" icon="el-icon-refresh-right" @click="handleRefresh">重置</el-button>
		</el-form>
		<div class="margin-top20 margin-bottom20 row-me">
			<el-button type="primary" @click="handleBatchDel">批量删除</el-button>
			<el-button type="primary" @click="handleAdd">新增广告</el-button>
			<div class="flex1"></div>
			<el-button type="primary" @click="typeVisible = true">广告分类</el-button>
		</div>
		<el-table :data="tableData" border header-cell-class-name="table-header-style"
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" align="center" width="55"></el-table-column>
			<el-table-column type="index" align="center" width="80" label="序号"></el-table-column>
			<el-table-column align="center" width="80" label="排序" prop="sort"></el-table-column>
			<el-table-column label="封面图" width="100">
				<template slot-scope="scope">
					<el-image class="width50 height50" :src="scope.row.img" :preview-src-list="[scope.row.img]"></el-image>
				</template>
			</el-table-column>
			<el-table-column width="300" label="广告标题" prop="name"></el-table-column>
			<el-table-column align="center" label="广告时长(秒)" prop="duration"></el-table-column>
			<el-table-column align="center" label="投放地区" width="180">
				<template slot-scope="scope">
					<el-tag class="margin-right5" v-if="scope.row.provinceName">{{scope.row.provinceName}}</el-tag>
					<el-tag v-if="scope.row.cityName">{{scope.row.cityName}}</el-tag>
				</template>
			</el-table-column>
			<el-table-column align="typeName" label="广告分类" prop="typeName"></el-table-column>
			<el-table-column align="createTime" label="上传时间" prop="createTime"></el-table-column>
			<el-table-column prop="url" label="视频地址" align="center" width="100">
				<template slot-scope="scope">
					<a :href="scope.row.videoUrl" target="_blank" class="blue-text">点击查看</a>
				</template>
			</el-table-column>
			<el-table-column prop="id" label="二维码" align="center">
				<template slot-scope="scope">
					<el-button type="text" @click="lookQrcode(scope.row)">点击查看</el-button>
				</template>
			</el-table-column>
			<el-table-column align="center" label="状态">
				<template slot-scope="{row}">
					<span>{{row.status==1?'开始':row.status==2?'关闭':''}}</span>
				</template>
			</el-table-column>
			<el-table-column align="center" label="操作" width="120">
				<template slot-scope="scope">
					<el-button type="text" @click="handleAdd(scope.row)">编辑</el-button>
					<el-button type="text" @click="handleDel(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div class="margin-top10">
			<el-pagination background layout="->,total,sizes, prev, pager, next" :current-page="query.pageNumber"
				:page-sizes="[30, 40, 50, 60]" @size-change="handleSizeChange" :page-size="query.pageSize" :total="pageTotal"
				@current-change="handlePageChange"></el-pagination>
		</div>

		<!-- 新增编辑广告 -->
		<el-dialog :title="title" :visible.sync="visible" width="600px">
			<el-form :model="form" label-width="110px" ref="form" :rules="rules">
				<el-form-item label="广告名称" prop="name">
					<el-input v-model="form.name" class="width300" placeholder="请输入广告名称"></el-input>
				</el-form-item>
				<el-form-item label="广告分类" prop="typeId">
					<el-select v-model="form.typeId" placeholder="请选择广告分类" class="width300">
						<el-option v-for="(item,index) in adverTypeData" :key="index" :label="item.name"
							:value="item.id"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="投放地区">
					<el-cascader :props="props" v-model="form.area" :options="areaData" placeholder="请选择地区" class="width300"
						@change="areaChange">
					</el-cascader>
				</el-form-item>
				<el-form-item label="缩略图" prop="img">
					<el-image v-if="form.img" class="width100 height100 radius6 margin-right10" :src="form.img"
						:preview-src-list="[form.img]"></el-image>
					<el-button type="text" @click="clickImg">点击图片库</el-button>
				</el-form-item>
				<el-form-item label="视频上传">
					<singleUploadLocal message="仅支持.MP4格式" @input="getVideoData" isVideo :value="videoFileList">
					</singleUploadLocal>
				</el-form-item>
				<el-form-item label="排序">
					<el-input placeholder="请输入排序" v-model="form.sort" class="width300"></el-input>
				</el-form-item>
				<el-form-item label="状态" prop="status">
					<el-select placeholder="请选择状态" v-model="form.status" class="width300">
						<el-option label="开启" :value="1"></el-option>
						<el-option label="关闭" :value="2"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="投放结束时间" prop="endTime">
					<el-date-picker style="width:300px" v-model="form.endTime" type="datetime" placeholder="请选择投放结束时间"
						value-format="yyyy-MM-dd HH:mm:ss">
					</el-date-picker>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="visible = false">取 消</el-button>
				<el-button type="primary" @click="handleSave">确 定</el-button>
			</span>
		</el-dialog>

		<!-- 广告分类 -->
		<el-dialog title="广告分类" :visible.sync="typeVisible" width="40%">
			<el-table :data="typeTableData" border>
				<el-table-column label="分类名称" align="center">
					<template slot-scope="{row}">
						<el-input v-model="row.name" v-if="row.isEdit"></el-input>
						<span v-else>{{row.name}}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center" width="200">
					<template slot-scope="scope">
						<el-button type="text" v-if="scope.row.isEdit" @click="handleTypeAdd(scope.row)">保存</el-button>
						<el-button type="text" @click="$set(scope.row,'isEdit',true)" v-else>编辑</el-button>
						<el-popconfirm title="确认删除？" @confirm="handleTypeDel(scope.row.id)">
							<el-button slot="reference" type="text">删除</el-button>
						</el-popconfirm>
					</template>
				</el-table-column>
			</el-table>
			<div class="margin-top10">
				<el-pagination background layout="->,total,sizes, prev, pager, next" :current-page="typeQuery.pageNumber"
					:page-sizes="[10, 20, 30, 40]" @size-change="handleSizeTypeChange" :page-size="typeQuery.pageSize"
					:total="pageTypeTotal" @current-change="handlePageTypeChange"></el-pagination>
			</div>
			<div class="margin-top20 row-me center-all">
				<el-input v-model="typeQuery.name" placeholder="请输入分类名称" class="margin-right20 width300"></el-input>
				<el-button type="primary" @click="handleTypeAdd">新增</el-button>
			</div>
			<span slot="footer">
				<el-button type="primary" @click="typeVisible = false">关 闭</el-button>
			</span>
		</el-dialog>

		<el-dialog title="二维码" :visible.sync="qrcodeVisible" width="40%">
			<div class="column-me center-all font-size16">
				<div class="row-me margin-top20">
					<div class="shijuan">
						App二维码 ：
					</div>
					<div>
						<div class="row-me flex-end2">
							<div id="qrCode" class="margin-top10 ">
								<div id="code" ref="appQrCodeUrl" title="" align="center"></div>
							</div>
							<span class="margin-left10" @click="handleDownloadAppQrIMg"> <i
									class="el-icon-download"></i>点击下载二维码</span>
						</div>
					</div>
				</div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="qrcodeVisible = false">关闭</el-button>
			</span>
		</el-dialog>

		<imgLibrary ref="imgLibrary" @handleImgOk="handleImgOk"></imgLibrary>
	</div>
</template>

<script>
	import uploadLocal from "@/components/Upload/multiUploadLocal"
	import singleUploadLocal from "@/components/Upload/singleUploadLocal"
	import imgLibrary from "@/components/imgLibrary"
	import QRCode from 'qrcodejs2';
	export default {
		components: {
			uploadLocal,
			singleUploadLocal,
			imgLibrary
		},
		data() {
			return {
				query: {
					pageNumber: 1,
					pageSize: 30
				},
				pageTotal: 0,
				adverTypeData: [],
				tableData: [],
				multipleSelection: [],
				qrcodeVisible: false,
				form: {},
				visible: false,
				props: {
					value: 'id',
					label: 'name',
					checkStrictly: true,
					multiple: true
				},
				fileList: [],
				title: '',
				areaData: [],
				videoFileList: [],
				rules: {
					name: {
						required: true,
						message: '请输入广告名称',
						trigger: 'blur'
					},
					typeId: {
						required: true,
						message: '请选择广告类型',
						trigger: 'change'
					},
					img: {
						required: true,
						message: '请上传缩略图',
						trigger: 'change'
					},
					status: {
						required: true,
						message: '请选择状态',
						trigger: 'change'
					},
					endTime: {
						required: true,
						message: '请选择投放结束时间',
						trigger: 'change'
					}
				},
				typeVisible: false,
				typeQuery: {
					pageNumber: 1,
					pageSize: 10
				},
				pageTypeTotal: 0,
				typeTableData: []
			}
		},
		mounted() {
			this.getAdverData()
			this.getAllArea()
			this.getData()
			this.getTypeData()
		},
		methods: {
			//获取省市区树
			async getAllArea() {
				const res = await this.$get('/admin/area/getAllArea')
				if (res.code == 1000) {
					this.areaData = this.$.getTreeData(res.data)
					this.areaData.unshift({
						adcode: '0',
						name: '默认',
						parentId: 0,
						id: '0'
					})
				}
			},
			//获取选中的图片
			handleImgOk(data) {
				this.$set(this.form, 'img', data)
			},
			//点击图片库
			clickImg() {
				this.$refs.imgLibrary.show()
			},
			//批量删除
			handleBatchDel() {
				this.$confirm('确定要批量删除已选中的题目吗？', '提示', {
					type: 'warning'
				}).then(() => {
					if (this.multipleSelection.length == 0) return
					let ids = Array.from(this.multipleSelection, ({
						id
					}) => id)
					this.$postForm('/admin/videos/adverDelete', {
						ids
					}).then(res => {
						if (res.code == 1000) {
							this.$message.success('批量删除成功')
							this.getData()
							this.multipleSelection = []
						}
					})
				}).catch(() => {})
			},
			//获取广告分类数据
			async getTypeData() {
				const res = await this.$postForm('/admin/videos/adverTypeAll', this.typeQuery)
				if (res.code == 1000) {
					this.typeTableData = res.data.list
					this.pageTypeTotal = res.data.totalRow
				}
			},
			//分类分页
			handlePageTypeChange(val) {
				this.typeQuery.pageNumber = val
				this.getTypeData();
			},
			handleSizeTypeChange(val) {
				this.typeQuery.pageSize = val
				this.getTypeData();
			},
			// 新增编辑分类
			handleTypeAdd(row) {
				if (row.id) {
					this.$post('/admin/videos/adverTypeUpdate', {
						id: row.id,
						name: row.name
					}).then(res => {
						if (res.code == 1000) {
							this.$message.success('编辑成功')
							this.getTypeData()
							row.isEdit = false
						}
					})
				} else {
					this.$post('/admin/videos/adverTypeSave', {
						name: this.typeQuery.name
					}).then(res => {
						if (res.code == 1000) {
							this.$message.success('新增成功')
							this.getTypeData()
							this.typeQuery.name = ''
						}
					})
				}
			},
			//删除分类
			async handleTypeDel(id) {
				console.log(id, "idd")
				const res = await this.$postForm('/admin/videos/adverTypeDelete', {
					id
				})
				if (res.code == 1000) {
					this.$message.success('删除成功')
					this.getTypeData()
				}
			},
			//投放地区
			areaChange(val) {
				this.form.citySheng = []
				this.form.cityShi = []
				if (val.length != 0) {
					for (let item of val) {
						if (item[0]) {
							this.form.citySheng.push(item[0])
						}
						if (item[1]) {
							this.form.cityShi.push(item[1])
						}
					}
				}
				this.form.citySheng = [...new Set(this.form.citySheng)]
				this.form.cityShi = [...new Set(this.form.cityShi)]
			},
			handleAdd(row) {
				if (row.id) {
					this.title = '编辑视频'
					this.form = JSON.parse(JSON.stringify(row))
					if (this.form.videoUrl) {
						this.videoFileList = [{
							name: this.form.videoUrl,
							url: this.form.videoUrl
						}]
					}
				} else {
					this.title = '新增视频'
					this.form = {}
					this.videoFileList = []
				}
				this.visible = true
			},
			//删除
			async handleDel(id) {
				const res = await this.$postForm('/admin/videos/adverDelete', {
					ids: [id]
				})
				if (res.code == 1000) {
					this.$message.success('删除成功')
					this.getData()
				}
			},
			// 获取缩略图
			getImgData(data) {
				this.form.img = data.toString()
			},
			//获取视频
			getVideoData(data) {
				if (data && data.length != 0) {
					this.form.videoUrl = data[0].url
					this.form.duration = data[0].duration
				}
			},
			getProvince() {
				var vm = this;
				return new Promise(function(resolve) {
					vm.$get('/admin/area/getProvince')
						.then(function(response) {
							response.data.unshift({
								name: '默认',
								id: '0'
							});
							vm.citys = response.data;
							resolve();
						});
				});
			},
			getCity(val) {
				var vm = this;
				return new Promise(function(resolve) {
					if (val == undefined || val == '0') {
						resolve([{
							name: '默认',
							id: ''
						}]);
					} else {
						vm.$get('/admin/area/getCities', {
								provinceId: val,
							})
							.then(function(response) {
								resolve(response.data);
							});
					}
				});
			},
			//加载省市选择项
			lazyLoad(node, resolve) {
				let vm = this;
				if (node.level == 0) {
					this.getProvince(node.value).then(() => {
						const nodes = vm.citys.map(item => ({
							value: item.id + '_' + '0_' + item.name,
							label: item.name,
							leaf: node.level >= 2
						}));
						resolve(nodes);
					});
				} else {
					this.getCity(node.value.split('_')[0]).then(city => {
						const nodes = city.map(item => ({
							value: item.id + '_' + '1_' + item.name,
							label: item.name,
							leaf: node.level >= 2
						}));
						resolve(nodes);
					});
				}
			},
			// 新增编辑广告
			handleSave() {
				this.$refs['form'].validate((valid) => {
					if (valid) {
						if (this.$.isEmpty(this.form.videoUrl)) {
							this.$message.warning('请上传视频!')
							return
						}
						this.form.cityShi = this.form.cityShi ? this.form.cityShi.toString() : this.form.cityShi
						this.form.citySheng = this.form.citySheng ? this.form.citySheng.toString() : this.form.citySheng
						let url = '/admin/videos/adverSave'
						if (this.form.id) {
							url = '/admin/videos/adverUpdate'
						}
						this.$post(url, this.form).then(res => {
							if (res.code == 1000) {
								this.$message.success('操作成功')
								this.getData()
								this.visible = false
							}
						})
					} else {
						return false;
					}
				});
			},
			// App二维码
			handleAppQrcode(row) {
				var vm = this;
				setTimeout(function() {
					vm.$refs.appQrCodeUrl.innerHTML = '';
					vm.$refs.appQrCodeUrl.name = row.id + "-" + row.title;
					var qrcode = new QRCode('code', {
						text: 'https://admin.shuatibang.com/h5/login.html?{"type":"video","id":"' + row.id +
							'","appid":"' + row.appid + '"}', // 需要转换为二维码的内容
						width: 150,
						height: 150,
						colorDark: '#000000',
						colorLight: '#ffffff',
						correctLevel: QRCode.CorrectLevel.H
					});
				}, 200);
			},
			// 点击下载图片
			handleDownloadAppQrIMg() {
				// 这里是获取到的图片base64编码
				var name = this.$refs.appQrCodeUrl.name;
				var img = document.getElementById('code').getElementsByTagName('img')[0];
				const imgUrl = img.src;
				// 如果浏览器支持msSaveOrOpenBlob方法（也就是使用IE浏览器的时候），那么调用该方法去下载图片
				if (window.navigator.msSaveOrOpenBlob) {
					let bstr = atob(imgUrl.split(',')[1]);
					let n = bstr.length;
					let u8arr = new Uint8Array(n);
					while (n--) {
						u8arr[n] = bstr.charCodeAt(n);
					}
					let blob = new Blob([u8arr]);
					window.navigator.msSaveOrOpenBlob(blob, name + '.' + 'png');
				} else {
					// 这里就按照chrome等新版浏览器来处理
					let a = document.createElement('a');
					a.href = imgUrl;
					a.setAttribute('download', name + '.' + 'png');
					a.click();
				}
			},
			// 点击查看二维码弹框
			lookQrcode(row) {
				var vm = this;
				this.qrcodeVisible = true;
				this.handleAppQrcode(row)
			},
			//分页
			handlePageChange(val) {
				this.query.pageNumber = val
				this.getData();
			},
			handleSizeChange(val) {
				this.query.pageSize = val
				this.getData();
			},
			//获取数据
			async getData() {
				const res = await this.$postForm(
					`/admin/videos/adverlAll?pageNumber=${this.query.pageNumber}&pageSize=${this.query.pageSize}`, this.query)
				if (res.code == 1000) {
					this.tableData = res.data.list
					this.pageTotal = res.data.totalRow
				}
			},
			// 多选操作
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			//获取视频广告分类下拉
			async getAdverData() {
				const res = await this.$postForm('/admin/videos/adverTypeList', this.query)
				if (res.code == 1000) {
					this.adverTypeData = res.data.list
				}
			},
			handleSearch() {
				this.query.pageNumber = 1
				this.getData();
			},
			handleRefresh() {
				this.query = {
					pageNumber: 1,
					pageSize: 30
				}
				this.getData();
			}
		}
	}
</script>

<style>
</style>